﻿using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;

namespace Cirrostrata.CycleList
{
    /// <summary>
    /// </summary>
    public class CycleList : ListBox
    {
        static CycleList()
        {
            DefaultStyleKeyProperty.OverrideMetadata(typeof(CycleList), new FrameworkPropertyMetadata(typeof(CycleList)));
        }

        public CycleList()
        {
            SelectionMode = SelectionMode.Single;
        }

        protected override DependencyObject GetContainerForItemOverride()
        {
            return new CycleListItem();
        }

        protected override void OnMouseDown(MouseButtonEventArgs e)
        {
            SelectNextItem();
            e.Handled = true;
        }

        protected override void OnSelectionChanged(SelectionChangedEventArgs e)
        {
            var cyclePanel = this.FindVisualChild<CyclePanel>();

            if (cyclePanel != null)
                cyclePanel.InvalidateVisual();

            e.Handled = true;
        }

        protected void SelectNextItem()
        {
            if (SelectedIndex == Items.Count - 1)
                SelectedIndex = 0;
            else
                SelectedIndex++;

            Items.MoveCurrentTo(Items[SelectedIndex]);
            SetSelectedItems(new[] { Items[SelectedIndex] });
        }
    }
}
